<template>
  <!-- 告警规则配置 弹窗 -->
  <a-modal
    v-model:open="visible"
    class="addRule"
    destroyOnClose
    :width="modelWidth"
    @cancel="cancel"
    centered
  >
    <template v-slot:title>
      <div class="mainTitle">
        {{ props.isEdit ? "编辑告警规则" : "新增告警规则" }}
      </div>
    </template>
    <a-divider />
    <div class="titleContent">
      <div class="title">
        基础信息配置<span class="subTitle">用于告警规则的基础信息</span>
      </div>
    </div>
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
    >
      <a-form-item label="告警规则名称" name="ruleName">
        <a-input
          v-model:value="form.ruleName"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="告警等级" name="warnLevel">
        <a-select
          ref="select"
          v-model:value="form.warnLevel"
          class="formSelect"
          placeholder="请选择"
        >
          <a-select-option
            v-for="item in WARN_LEVEL_LIST"
            :value="item.value"
            :key="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="规则状态" name="status">
        <a-select
          ref="select"
          v-model:value="form.status"
          class="formSelect"
          placeholder="请选择"
        >
          <a-select-option
            v-for="item in RULE_STATUS_LIST"
            :value="item.value"
            :key="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="告警规则备注">
        <a-input
          v-model:value="form.comment"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="告警信息" name="warnMessage">
        <a-input
          v-model:value="form.warnMessage"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="告警触发" name="maintenanceAdvice">
        <a-input
          v-model:value="form.maintenanceAdvice"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="状态分类" name="warnType">
        <a-select
          ref="select"
          v-model:value="form.warnType"
          class="formSelect"
          placeholder="请选择"
          allowClear
        >
          <a-select-option
            v-for="item in listWarnType"
            :value="item.val"
            :key="item.val"
          >
            {{ item.title }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-divider />
      <div class="titleContent">
        <div class="title">
          告警规则配置<span class="subTitle"
            >通过规则配置，可支持自定义配置需要监测的设备告警</span
          >
        </div>
      </div>
      <a-card style="margin-top: 20px; width: 100%">
        <template #title>
          <div class="title" style="margin-top: 0">
            01 触发条件
            <span class="subTitle">满足触发条件时启动规则，最多可设置3条</span>
          </div>
        </template>
        <a-form-item
          label="触发条件设定"
          name="triggerType"
          labelAlign="left"
          class="specialLine"
        >
          <a-radio-group v-model:value="form.triggerType">
            <a-radio :value="1">满足所有条件触发</a-radio>
            <a-radio :value="2">满足任意条件触发</a-radio>
          </a-radio-group>
        </a-form-item>
        <div class="errorRule">
          <label
            for="form_item_triggerType"
            class="ant-form-item-required"
            title="触发条件设定"
            >告警规则：</label
          >
        </div>
        <a-card
          v-for="(item, index) in form.warnRuleConditionList"
          :key="index"
          :title="`告警规则${index + 1}`"
          :headStyle="{
            'font-size': '14px',
            'font-weight': 'normal',
          }"
          :style="{ 'margin-top': index > 0 ? '20px' : 0 }"
        >
          <a-form-item
            label="触发方式："
            :rules="[
              { required: true, message: '请选择触发方式', trigger: 'change' },
            ]"
            :name="['warnRuleConditionList', index, 'alarmPoint']"
            :labelCol="{ style: { width: '100px' } }"
          >
            <a-select
              ref="select"
              v-model:value="item.alarmPoint"
              class="formSelect"
              placeholder="请选择"
              allowClear
            >
              <!-- @change="
                handleSearchCustomAlarmPoint(item.alarmPoint === 1 ? 1 : 2)
              " -->
              <a-select-option
                v-for="item in RULE_TYPE_LIST"
                :value="item.value"
                :key="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="告警层级"
            :rules="[
              { required: true, message: '请选择告警层级', trigger: 'change' },
            ]"
            :name="['warnRuleConditionList', index, 'warnEquipLevel']"
            :labelCol="{ style: { width: '100px' } }"
          >
            <a-select
              ref="select"
              v-model:value="item.warnEquipLevel"
              class="formSelect"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item in WARN_EQUIP_LEVEL_LIST"
                :value="item.value"
                :key="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="参数代码"
            :rules="[
              { required: true, message: '请选择参数代码', trigger: 'change' },
            ]"
            :name="['warnRuleConditionList', index, 'paramCode']"
            :labelCol="{ style: { width: '100px' } }"
          >
            <a-select
              v-model:value="item.paramCode"
              show-search
              optionFilterProp="label"
              placeholder="请输入或者选择"
              class="formSelect"
              v-if="item.alarmPoint === 1"
            >
              <a-select-option
                v-for="item in customAlarmPoint"
                :key="item.id"
                :value="item.code"
                :label="item.code"
              >
                {{ item.name }}({{ item.code }})
              </a-select-option>
            </a-select>
            <a-select
              v-model:value="item.paramCode"
              show-search
              placeholder="请输入或者选择"
              class="formSelect"
              v-else
            >
              <a-select-option
                v-for="item in paramCodeOptions"
                :key="item.id"
                :value="item.code"
              >
                {{ item.name }}({{ item.code }})
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="持续时间"
            :rules="[
              { required: true, message: '请选择持续时间', trigger: 'change' },
            ]"
            :name="['warnRuleConditionList', index, 'keepMinutes']"
            :labelCol="{ style: { width: '100px' } }"
          >
            <a-select
              ref="select"
              v-model:value="item.keepMinutes"
              class="formSelect"
              placeholder="请选择"
            >
              <a-select-option
                v-for="item in KEEP_MINUTE_LIST"
                :value="item.value"
                :key="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="判断条件"
            :rules="[
              {
                required: item.alarmPoint === 2,
                message: '请选择判断条件',
                trigger: 'blur',
              },
            ]"
            :name="['warnRuleConditionList', index, 'judgeNumber']"
            :labelCol="{ style: { width: '100px' } }"
          >
            <a-select
              ref="select"
              v-model:value="item.judgeCondition"
              class="formSelect"
              placeholder="请选择"
              style="width: 150px"
              :disabled="item.alarmPoint === 1"
            >
              <a-select-option
                v-for="item in JUDGE_CONDITION_LIST"
                :value="item.value"
                :key="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
            <a-form-item-rest>
              <a-input
                v-model:value="item.judgeNumber"
                class="formInput"
                placeholder="请输入"
                style="width: 200px"
                :disabled="item.alarmPoint === 1"
              />
            </a-form-item-rest>
          </a-form-item>
          <template #extra>
            <a-popconfirm
              title="确定删除该数据?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="confirm(index)"
            >
              <a-button type="text" danger>删除</a-button>
            </a-popconfirm>
          </template>
        </a-card>
        <a-button
          type="primary"
          class="filterBtn greenBtn"
          @click="addWarnRule"
          style="width: 100%; margin-top: 15px"
          ><PlusOutlined />新增规则</a-button
        >
      </a-card>
      <a-card style="margin-top: 20px; width: 100%">
        <template #title>
          <div class="title" style="margin-top: 0">
            02 静默时间
            <span class="subTitle"
              >若已配置静默时间，则告警规则触发告警后，在设定的时间范围内将不再重复生成告警和通知。超出设定时间告警仍未恢复，则会再次触发告警</span
            >
          </div>
        </template>
        <a-form-item
          label="静默时间"
          name="silenceTime"
          :labelCol="{ style: { width: '100px' } }"
        >
          <a-select
            ref="select"
            v-model:value="form.silenceTime"
            class="formSelect"
            placeholder="请选择"
          >
            <a-select-option
              v-for="item in SILENT_MINUTE_LIST"
              :value="item.value"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-card>
      <a-card style="margin-top: 20px; width: 100%">
        <template #title>
          <div class="title" style="margin-top: 0">
            03 生效时间
            <span class="subTitle"
              >设置生效时间，可以控制系统在某个时段产生有效告警，并在该时段通知联系人</span
            >
          </div>
        </template>
        <a-form-item
          label="生效时间"
          name="effectiveTimeType"
          :labelCol="{ style: { width: '100px' } }"
        >
          <a-select
            ref="select"
            v-model:value="form.effectiveTimeType"
            class="formSelect"
            placeholder="请选择"
          >
            <a-select-option
              v-for="item in EFFECT_TIME_LIST"
              :value="item.value"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="设定时段"
          name="timeRange"
          :labelCol="{ style: { width: '100px' } }"
          :rules="[
            {
              required: form.effectiveTimeType === 2,
              trigger: 'blur',
              message: '请选择时段',
            },
          ]"
        >
          <a-time-range-picker
            v-model:value="form.timeRange"
            class="formSelect"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            :disabled="form.effectiveTimeType === 1"
        /></a-form-item>
      </a-card>
      <a-divider />
      <div class="titleContent">
        <div class="title">
          工单自动化配置<span class="subTitle"
            >当告警产生时，将自动根据该告警生成对应的工单</span
          >
        </div>
        <a-form-item
          label="生成工单"
          :labelCol="{ style: { width: '100px' } }"
          name="isAutoWorkOrder"
        >
          <a-select
            ref="select"
            v-model:value="form.isAutoWorkOrder"
            class="formSelect"
            placeholder="请选择"
          >
            <a-select-option
              v-for="item in IS_AUTO_WORK_ORDER_LIST"
              :value="item.value"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </div>
    </a-form>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确定</a-button
        >
      </div>
    </template>
  </a-modal>
</template>

<script setup>

import {
  EFFECT_TIME_LIST,
  IS_AUTO_WORK_ORDER_LIST,
  JUDGE_CONDITION_LIST,
  KEEP_MINUTE_LIST,
  RULE_STATUS_LIST,
  RULE_TYPE_LIST,
  SILENT_MINUTE_LIST,
  WARN_EQUIP_LEVEL_LIST,
  WARN_LEVEL_LIST,
} from "@/constants/stationConfig.js"
const $api = inject("$api")
const modelWidth = computed(() => (window.innerWidth > 1610 ? "58%" : "85%"))
const props = defineProps({
  addWarnRuleVisible: {
    type: Boolean,
    default: false,
  },
  isEdit: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
    default: () => ({}),
  },
  list: {
    type: Array,
    default: [],
  },
})

const loading = ref(false)
const visible = ref(props.visible)
const formRef = ref()
const emits = defineEmits(["update:visible", "refresh"])
watch(
  () => props.addWarnRuleVisible,
  (val) => {
    visible.value = val
    if (val) {
      if (props.isEdit) {
        getEditMessage()
      }
    }
  },
  { immediate: true }
)
const listWarnName = ref([])
const listWarnType = ref([])
watch(
  () => props.list,
  (val) => {
    listWarnType.value = val.reduce((acc, curr) => {
      if (curr.children && Array.isArray(curr.children)) {
        return [...acc, ...curr.children]
      }
      return acc
    }, [])
    //form.value.statusType = listWarnType.value[0].val
  },
  {
    immediate: true,
  }
)
const labelCol = {
  style: {
    width: "120px",
  },
}

const form = ref({
  ruleName: "",
  warnLevel: 1,
  status: 0,
  comment: "",
  warnMessage: "",
  maintenanceAdvice: "",
  triggerType: 1,
  warnType: "",
  warnRuleConditionList: [
    {
      alarmPoint: 1,
      paramCode: "",
      keepMinutes: null,
      warnEquipLevel: 1,
      judgeCondition: null,
      judgeNumber: null,
    },
  ],
  silenceTime: 0,
  effectiveTimeType: 1,
  timeRange: [],
  isAutoWorkOrder: 0,
})

const rules = {
  ruleName: [
    { required: true, message: "请输入告警规则名称", trigger: "blur" },
  ],
  warnLevel: [{ required: true, message: "请选择告警等级", trigger: "change" }],
  status: [{ required: true, message: "请选择规则状态", trigger: "change" }],
  warnMessage: [{ required: true, message: "请输入告警信息", trigger: "blur" }],

  triggerType: [
    { required: true, message: "请选择触发条件", trigger: "change" },
  ],
  /*  statusType: [
    { required: true, message: "请选择状态分类", trigger: "change" },
  ], */

  warnRuleConditionList: [{ required: true, message: "", trigger: "change" }],
  silenceTime: [
    { required: true, message: "请选择静默时间", trigger: "change" },
  ],
  effectiveTimeType: [
    { required: true, message: "请选择生效时间", trigger: "change" },
  ],
  /*   timeRange: [
    {
      required: isRequired.value,
      validator: (rule, val) => {
        console.log(1111, rule)
      },
    },
  ], */
  isAutoWorkOrder: [
    { required: true, message: "请选择自动生成工单", trigger: "change" },
  ],
}
const isRequired = ref(false)
watch(
  () => form.value.effectiveTimeType,
  (val) => {
    isRequired.value = val === 2
  }
)
watch(
  () => props.visible,
  (val) => {
    visible.value = val
    if (val && props.isEdit) {
      form.value = {
        ...props.rowData,
      }
      handleSearchCustomAlarmPoint(1)
      handleSearchCustomAlarmPoint(2)
    }
  }
)

const cancel = () => {
  emits("update:addWarnRuleVisible", false)
  formRef.value?.resetFields()
}
const paramCodeOptions = ref([])
const customAlarmPoint = ref([])
const handleSearchCustomAlarmPoint = async (type) => {
  const params = {
    /*  size: 10,
    current: 1, */
    alarmPoint: type,
  }
  const res = await $api.paramCodeList(params)
  if (type === 1) {
    customAlarmPoint.value = res.data
  } else {
    paramCodeOptions.value = res.data
  }
  /* .map((item) => ({
    code: item.code,
    name: item.name,
  })) */
}
const addWarnRule = () => {
  if (form.value.warnRuleConditionList.length >= 3) {
    message.warning("最多可设置3条")
    return
  }
  form.value.warnRuleConditionList.push({
    alarmPoint: 1,
    paramCode: "",
    keepMinutes: null,
    warnEquipLevel: 1,
    judgeCondition: null,
    judgeNumber: null,
  })
}
const confirm = (index) => {
  if (form.value.warnRuleConditionList.length === 1) {
    message.warning("至少需设置一条规则")
    return false
  }
  form.value.warnRuleConditionList.splice(index, 1)
}
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    // TODO: 调用API保存数据
    if (props.isEdit) {
      // 编辑带上id
      form.value.id = props.rowData.id
    }
    let res
    if (!props.isEdit) {
      res = await $api.warnRuleAdd(form.value)
    } else {
      res = await $api.warnRuleEdit(form.value)
    }
    loading.value = false
    if (res.code === 0) {
      message.success(props.isEdit ? "编辑成功" : "新增成功")
      cancel()
      emits("getWarnRuleList")
    }
    message.success("保存成功")
    cancel()
    emits("refresh")
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}
const getEditMessage = async () => {
  const params = {
    id: props.rowData.id,
  }

  const res = await $api.getWarnRuleById(params)
  if (res.code === 0) {
    form.value = res.data
  }
}
onMounted(async () => {
  handleSearchCustomAlarmPoint(1)
  handleSearchCustomAlarmPoint(2)
})
</script>

<style lang="less" scoped>
.formInput,
.formSelect {
  width: 350px;
}
.ant-form-item {
  margin-top: 20px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.title {
  font-size: 18px;
  font-weight: 500;
  color: #fff;
  line-height: 24px;
  margin-top: 30px;
}
.subTitle {
  font-size: 12px;
  font-weight: 400;
  color: #646a73;
  line-height: 20px;
  margin-left: 5px;
}
.mainTitle {
  font-size: 22px;
  font-weight: 500;
}
::v-deep(.ant-card-body) {
  display: flex;
  flex-wrap: wrap;
}
.errorRule {
  display: inline-block;
  flex-grow: 0;
  overflow: hidden;
  white-space: nowrap;
  text-align: start;
  vertical-align: middle;
  width: 300px;
  margin-top: 20px;
  .ant-form-item-required {
    position: relative;
    display: inline-flex;
    align-items: center;
    max-width: 100%;
    height: 32px;
    color: rgba(255, 255, 255, 0.85);
    font-size: 14px;
    &::before {
      display: inline-block;
      margin-inline-end: 4px;
      color: #dc4446;
      font-size: 14px;
      font-family: SimSun, sans-serif;
      line-height: 1;
      content: "*";
    }
  }
}
::v-deep(.specialLine) {
  display: block !important;
  width: 100%;
}
</style>
